<template>
  <div style="display: flex; justify-content: space-between">
    <el-button type="primary" @click="showModal">添加商品</el-button>
    <div>
      <el-input
        v-model="queryInfo.keywords"
        placeholder="输入关键词查询"
        style="width: 200px; margin-right: 10px"
      ></el-input>
      <el-button type="" @click="getList">查询</el-button>
    </div>
  </div>
  <div class="goods-list-management">
    <el-table :data="goodsList" style="width: 100%" height="450px">
      <el-table-column prop="cover" label="封面图">
        <template #default="scope">
          <img
            :src="
              scope.row.images[0]?.url.includes('http')
                ? scope.row.images[0]?.url
                : origin + scope.row.images[0]?.url
            "
            alt=""
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="goodsName"
        label="商品名称"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span class="goods-title" @click="gotoDetail(scope.row)">
            {{ scope.row.goodsName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="info"
        label="介绍"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column prop="classificationDtos" label="种类" width="140">
        <template #default="scope">
          <el-tag
            type="success"
            v-for="(item, index) in scope.row.classificationDtos"
            style="margin-right: 4px"
          >
            {{ item.title }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="goodsNum" label="库存"></el-table-column>
      <el-table-column prop="price" label="价格(元)"></el-table-column>
      <!-- <el-table-column prop="producer" label="厂商"></el-table-column> -->

      <el-table-column
        prop="productTime"
        width="120"
        label="生产时间"
      ></el-table-column>
      <el-table-column prop="address" label="生产地址"></el-table-column>

      <el-table-column label="操作" v-if="userInfo.role === 1" width="180">
        <template #default="scope">
          <div style="display: flex; justify-content: space-between">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              style="width: 44px; border: none"
              :action="`/api/goods/uploadGoodsImage?goodsId=${goodsId}`"
              name="file"
            >
              <el-button
                type="primary"
                :icon="Upload"
                circle
                @click="text(scope.row)"
              />
            </el-upload>
            <el-button
              type="primary"
              :icon="Tickets"
              circle
              @click="showDrawer(scope.row)"
            />
            <el-button
              type="primary"
              :icon="Edit"
              circle
              @click="showEdit(scope.row)"
            />

            <el-popconfirm
              title="你确定删除吗?"
              @confirm="deleteGoodsById(scope.row.id)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button :icon="Delete" circle />
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total"
      />
    </div>
  </div>

  <el-drawer
    v-model="drawerVisible"
    :title="currentGoodsDetail.goodsName"
    :direction="direction"
    :before-close="handleCloseDrawer"
  >
    <ul class="goods-detail">
      <li>
        <span class="name">商品名称：</span>
        <span class="info">{{ currentGoodsDetail.goodsName }}</span>
      </li>
      <li>
        <span class="name">商品价格：</span>
        {{ currentGoodsDetail.price }} 元
      </li>

      <li>
        <span class="name">类别：</span>

        <div class="goods-norms">
          <el-tag
            v-for="(item, index) in currentGoodsDetail.classificationTitles"
            :key="index"
          >
            {{ item }}
          </el-tag>
        </div>
      </li>
      <li>
        <span class="name">商品库存：</span>
        <span class="info">{{ currentGoodsDetail.goodsNum }}</span>
      </li>
      <li>
        <span class="name">生产地址：</span>
        {{ currentGoodsDetail.address }}
      </li>
      <li>
        <span class="name">商品介绍：</span>
        <span class="info">{{ currentGoodsDetail.info }}</span>
      </li>

      <li>
        <span class="name">上架时间：</span>
        <span class="info">{{ currentGoodsDetail.groundingTime }}</span>
      </li>
      <li>
        <span class="name">商品种类：</span>
        <div class="goods-norms info">
          <el-tag
            type=""
            v-for="(item, index) in currentGoodsDetail.normsTitles"
            :key="index"
          >
            {{ item }}
          </el-tag>
        </div>
      </li>

      <li>
        <span class="name">商品图片：</span>
        <div class="goods-img">
          <img
            :src="item.url.includes('http') ? item.url : origin + item.url"
            alt=""
            style="width: 50px; height: 50px"
            v-for="(item, index) in currentGoodsDetail.images"
            :key="index"
          />
        </div>
      </li>
    </ul>
  </el-drawer>

  <el-dialog
    v-model="dialogVisible"
    :title="type === 'add' ? '添加商品' : '编辑商品'"
    @close="handleClose"
    width="600px"
  >
    <el-form
      :model="addForm"
      :rules="formRules"
      label-width="120px"
      ref="addForm"
    >
      <el-form-item label="商品名称" prop="goodsName" style="width: 90%">
        <el-input v-model="addForm.goodsName"></el-input>
      </el-form-item>
      <!-- <el-form-item label="商品图片" prop="cover" style="width: 90%">
        <el-input v-model="addForm.cover"></el-input>
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          style="width: 80px"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          name="cover"
        >
          <img
            v-if="addForm.images"
            v-for="(item, index) in addForm.images"
            :key="index"
            :src="item.url"
            width="40px"
            height="40px"
            class="avatar"
            style="margin-right: 10px"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item> -->
      <el-form-item label="商品分类" prop="classificationId">
        <!-- <el-input v-model="addForm.classificationId"></el-input> -->
        <el-select
          v-model="addForm.classificationId"
          placeholder="请选择商品分类"
          style="width: 90%"
          multiple
        >
          <el-option
            v-for="item in goodsTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格" prop="normsId">
        <!-- <el-input v-model="addForm.classificationId"></el-input> -->
        <el-select
          v-model="addForm.normsId"
          placeholder="请选择商品规格"
          style="width: 90%"
          multiple
        >
          <el-option
            v-for="item in goodsNormsList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上架数量" prop="goodsNum" style="width: 90%">
        <!-- <el-input v-model="addForm.goodsNum"></el-input> -->
        <el-input-number v-model="addForm.goodsNum" :min="1" />
      </el-form-item>

      <el-form-item label="价格" prop="price" style="width: 90%">
        <el-input v-model="addForm.price"></el-input>
      </el-form-item>

      <el-form-item label="生产日期" prop="productTime" style="width: 90%">
        <!-- <el-input v-model="addForm.productTime"></el-input> -->
        <el-date-picker
          v-model="addForm.productTime"
          type="date"
          placeholder="选择生产日期"
        />
      </el-form-item>
      <!-- <el-form-item label="生产厂商" prop="productor" style="width: 90%">
        <el-input v-model="addForm.productor"></el-input>
      </el-form-item> -->
      <el-form-item label="生产地址" prop="address" style="width: 90%">
        <el-input v-model="addForm.address"></el-input>
      </el-form-item>

      <el-table :data="addForm.tableData" style="width: 100%">
        <el-table-column
          v-for="(item, index) in addForm.tableHeader"
          :prop="item.keys"
          :label="item.label"
          :key="index"
        >
          <template #default="scope">
            <span v-if="scope.row.isSet">
              <el-form-item
                label-width="0"
                :prop="'tableData.' + scope.$index + '.' + item.keys"
                style="margin-bottom: 0"
              >
                <el-input
                  width="100px"
                  style="width: 100%"
                  v-model="scope.row[item.keys]"
                ></el-input>
              </el-form-item>
            </span>
            <span v-else>
              {{ scope.row[item.keys] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="!scope.row.isSet"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button @click="handleAdd()" style="width: 100%; margin-top: 10px">
        add
      </el-button>
    </el-form>

    <template #footer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { Edit, Delete, Tickets, Plus, Upload } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'
</script>

<script>
import dayjs from 'dayjs'
import {
  getClassificationList,
  getNormsList,
  getGoodsList,
  deleteGoods,
  editGoods,
  getGoodsDetail,
  createGoods
} from '../api/goods.js'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      origin: 'http://43.136.166.102:8090',
      drawerVisible: false,
      userInfo: JSON.parse(window.localStorage.getItem('user_info')),
      dialogVisible: false,
      goodsList: [],
      queryInfo: {
        keywords: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      addForm: {
        recipientName: '',
        phoneNumber: '',
        Goods: '',
        goodsNum: 1,
        tableHeader: [
          {
            label: '描述名称',
            keys: 'key'
          },
          {
            label: '值',
            keys: 'value'
          }
        ],
        tableData: [
          {
            key: '',
            value: ''
          }
        ]
      },
      type: 'add',
      formRules: {
        recipientName: [
          { required: true, message: '请输入收件人姓名', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      currentGoodsDetail: {},
      goodsTypeList: [],
      goodsNormsList: [],
      originGoodsNormsList: [],
      originGoodsTypeList: [],
      goodsId: ''
    }
  },
  methods: {
    text(row) {
      this.goodsId = row.id
    },
    showDrawer(row) {
      this.drawerVisible = !this.drawerVisible
      this.currentGoodsDetail = row
      this.getGoodsDetailById(row.id)
      console.log(row)
    },
    getGoodsDetailById(id) {
      getGoodsDetail(id).then((res) => {
        console.log('res', res)
      })
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getList()
    },
    handleCloseDrawer() {
      this.drawerVisible = false
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getList()
    },
    showModal() {
      this.dialogVisible = true
      this.addForm = {
        goodsNum: 1,
        tableHeader: this.addForm.tableHeader,
        tableData: []
      }
      this.type = 'add'
    },
    handlePick(value) {
      console.log(value)
      this.addForm.Goods = value.map((item) => item.name).join('')
    },
    handleClose() {},
    showEdit(info) {
      console.log('info', info)
      this.dialogVisible = true
      const newTableData = []
      Object.keys(info.infoMap).forEach((key) => {
        newTableData.push({
          key: key,
          value: info.infoMap[key]
        })
      })
      this.addForm = {
        ...info,
        tableHeader: this.addForm.tableHeader,
        tableData: newTableData
      }
      this.type = 'edit'
      this.addForm.classificationId = info.classificationDtos.map(
        (item) => item.id
      )
      this.addForm.normsId = info.normsDtos.map((item) => item.id)
    },
    getList() {
      getGoodsList(this.queryInfo).then((res) => {
        this.goodsList = res.list.map((item) => {
          return {
            ...item,
            productTime: dayjs(item.productTime).format('YYYY-MM-DD')
          }
        })
        this.total = res.total
      })
    },

    deleteGoodsById(id) {
      deleteGoods(id).then((res) => {
        this.getList()
        ElMessage.success('删除成功！')
      })
    },
    handleSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          console.log('valid.normsId', this.addForm)
          let params = {
            ...this.addForm,
            classificationDtos: this.originGoodsTypeList.filter((item) =>
              this.addForm.classificationId.includes(item.id)
            ),
            info: this.addForm.tableData
              .map((item) => {
                return `${item.key}：${item.value}`
              })
              .join('\n'),

            normsDtos: this.originGoodsNormsList.filter((item) =>
              this.addForm.normsId.includes(item.id)
            ),
            createTime: new Date()
          }
          delete params.normsId
          delete params.classificationId
          delete params.tableData
          delete params.tableHeader

          if (this.type === 'add') {
            params = {
              ...params,
              id: Math.floor(Math.random() * (999999 - 100000 + 1) + 100000)
            }

            createGoods(params).then((res) => {
              this.dialogVisible = false
              this.getList()
            })
          } else {
            editGoods(params).then((res) => {
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    handleAvatarSuccess(response, uploadFile) {
      // this.addForm.cover = URL.createObjectURL(uploadFile.raw)
      this.getList()
      this.$message.success('上传成功！')
    },
    gotoDetail(row) {
      window.open(`#/goods/${row.id}`)
    },
    handleAdd() {
      let row = {}
      this.addForm.tableHeader.forEach((item, index) => {
        row.isSet = true
      })
      this.addForm.tableData.push(row)
    },
    //编辑
    handleEdit(index, row) {
      row.isSet = true
      this.$set(this.addForm.tableData, index, row)
    },
    //删除
    handleDelete(index, row) {
      this.addForm.tableData.splice(index, 1)
    }
  },
  created() {
    this.getList()
    getClassificationList({ pageNum: 1, pageSize: 100 }).then((res) => {
      // this.total = res.total
      this.originGoodsTypeList = res.records
      this.goodsTypeList = res.records.map((item) => {
        return {
          label: item.title,
          value: item.id
        }
      })
    })
    getNormsList({ pageNum: 1, pageSize: 100 }).then((res) => {
      this.originGoodsNormsList = res.records
      this.goodsNormsList = res.records.map((item) => {
        return {
          label: item.title,
          value: item.id
        }
      })
    })
  }
}
</script>
<style lang="less" scoped>
.goods-list-management {
  // display: flex;
  justify-content: space-between;
  list-style-type: none;
  margin: 20px 0;
  align-items: center;

  .Goods-name {
    display: flex;
    align-items: center;
  }

  .def-name {
    background: linear-gradient(to right, #ff0000, #fc7544);
    color: #fff;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 37px;
    font-size: 22px;
    font-weight: 600;
    margin-right: 10px;
  }
  .no-def-name {
    background: #fff;
    color: #ff0000;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 37px;
    font-size: 22px;
    font-weight: 600;
    margin-right: 10px;
    border: 1px solid #ff0000;
  }
}

.goods-detail {
  list-style-type: none;
  padding: 0 10px;
  li {
    display: flex;
    padding: 4px 0;
    .name {
      color: #999;
      flex-basis: 90px;
      text-align: right;
      margin-right: 16px;
    }
    .info {
      flex: 1;
    }
    .goods-norms {
      span {
        margin: 4px;
      }
    }
    .goods-img {
      img {
        margin-right: 10px;
      }
    }
  }
}

.el-tab-pane {
  padding: 0 20px;
  padding-left: 40px;
}

.goods-title {
  cursor: pointer;
}
.goods-title:hover {
  color: #ea5512;
}
.avatar-uploader .el-upload {
  border: none;
}

// .el-upload {
//   border: 1px dashed #f5f7fa;
//   width: 100px;
//   height: 100px;
// }
</style>
